<template>
  <el-dialog :visible.sync="isShow" width="600px" class="enroll" :center="true">
    <div class="title" slot="title">用户注册</div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" @click="submit('form')">确 定</el-button>
    </span>
    <el-form :model="form" label-width="70px" :rules="rules" ref="form">
      <el-form-item class="item-img" label="头像" prop="avatar">
        <el-upload
          v-model="form.avatar"
          class="avatar-uploader"
          name="image"
          :action="baseUrl + '/uploads'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="form.avatar"
            :src="baseUrl + '/' + form.avatar"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="圆形码" prop="code">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="7" :offset="1">
            <img @click="codeClick" :src="codeUrl" alt class="get_rcode" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="16">
            <el-input v-model="form.rcode"></el-input>
          </el-col>

          <el-col :span="7" :offset="1">
            <el-button @click="getEnroll" :disabled="lock"
              >获取用户验证码</el-button
            >
            <p v-show="lock">
              还有 <span>{{ time }}s</span> 可继续获取
            </p>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { verify, register } from "@/api/register.js";
console.log(verify);
export default {
  data() {
    return {
      form: {
        username: "", //	是	string	用户名
        phone: "", //	是	string	手机号
        email: "", //	是	string	邮箱
        avatar: "", //	是	string	头像地址
        password: "", //	是	string	密码
        code: "",
        rcode: "", //	是	string	验证码
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
        ], //	是	string	用户名
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              const _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确手机号"));
              }
            },
          },
        ], //	是	string	手机号

        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确格式邮箱"));
              }
            },
            trigger: "blur",
          },
        ], //	是	string	邮箱
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }], //	是	string	头像地址
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            min: 6,
            max: 16,
            message: "密码为6到16位的字符",
            trigger: "change",
          },
        ], //	是	string	密码
        code: [{ required: true, message: "请输入圆形码", trigger: "change" }],
        rcode: [{ required: true, message: "请输入验证码", trigger: "change" }], //	是	string	验证码
      },
      isShow: false,
      imageUrl: "",
      baseUrl: process.env.VUE_APP_URL,
      codeUrl: "",
      time: 60,
      lock: false,
    };
  },
  watch: {
    isShow(newData) {
      if (newData == false) {
        this.$refs.form.resetFields();
      }
    },
  },
  methods: {
    codeClick() {
      this.codeUrl =
        process.env.VUE_APP_URL + "/captcha?type=sendsms&t=" + Date.now();
    },

    submit(formName) {
      this.$refs[formName].validate((result) => {
        if (result) {
          register(this.form)
            .then(() => {
              this.$refs["form"].resetFields();
              this.$message.success("注册成功!");
              this.isShow = false;
            })
            .catch((err) => {
              this.$message.error(err);
            });
        }
      });
    },
    getEnroll() {
      let time;
      console.log("btn");
      let num = 0;
      this.$refs.form.validateField(["code", "phone"], (errMessage) => {
        if (errMessage == "") {
          num++;
        }
      });
      if (num == 2) {
        this.lock = true;
        time = setInterval(() => {
          if (this.time > 0) {
            this.time--;
          } else if (this.time == 0) {
            clearInterval(time);
            this.lock = false;
            this.time = 60;
          }
        }, 1000);
        verify({
          //注册接口被抽离成方法
          code: this.form.code,
          phone: this.form.phone,
        })
          .then((res) => {
            this.$message.success(res.data.data.captcha + "");
            // if (res.data.message == "ok") {
            //   this.$message.success(res.data.data.captcha + "");
            // }
          })
          .catch((err) => {
            clearInterval(time);
            this.lock = false;
            this.time = 60;
            this.$message.error(err);
          });
      } else {
        this.$message.error("验证失败");
      }
    },
    handleAvatarSuccess(res) {
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  created() {
    this.codeClick();
  },
};
</script>

<style lang="less">
.enroll {
  .title {
    width: 600px;
    height: 53px;
    line-height: 53px;
    background: linear-gradient(to right, #02c3fa, #1395fa);
    font-size: 14px;
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 400;
    text-align: center;
    color: #fefefe;
    letter-spacing: 0px;
  }
  .el-dialog__header {
    padding: 0;
    .el-dialog__headerbtn {
      display: none;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .item-img {
    text-align: center;
  }
  .get_rcode {
    width: 100%;
    height: 40px;
  }
}
</style>
